package com.jigsawapp.movies.common;

import com.jigsawapp.movies.api.MoviesApi;

import java.util.regex.Pattern;

/**
 * Created by jigsaw on 2016/3/9.
 * Email: fadeblack307@163.com
 */
public class StringUtils {

    private final static Pattern emailer = Pattern
            .compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
    private final static Pattern userer = Pattern.compile("^[a-zA-z][a-zA-Z0-9_]{2,9}$");

    /**
     * 判断给定字符串是否空白串。 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串，返回true
     *
     * @param input
     * @return boolean
     */
    public static boolean isEmpty(String input) {
        if (input == null || "".equals(input))
            return true;

        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断是不是一个合法的电子邮件地址
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        if (email == null || email.trim().length() == 0)
            return false;
        return emailer.matcher(email).matches();
    }


    public static boolean isUsername(String user) {
        if (user == null || user.trim().length() == 0)
            return false;
        return userer.matcher(user).matches();
    }
    /**
     * 字符串转整数
     *
     * @param str
     * @param defValue
     * @return
     */
    public static int toInt(String str, int defValue) {
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
        }
        return defValue;
    }

    public static String buildMoviesUrl(String pagenum, String pagesize) {
        StringBuilder sb = new StringBuilder();
        sb.append(MoviesApi.MOVIES_URL);
        sb.append("pagenum/");
        sb.append(pagenum);
        sb.append("/");
        sb.append("pagesize/");
        sb.append(pagesize);
        return sb.toString();
    }
}
